package util

import (
	"fmt"
	"os"
	"path"
)

//EnsureDir ensure dir useable and check perm
func EnsureDir(p string, perm os.FileMode) error {
	dir := path.Dir(p)
	info, err := os.Stat(dir)
	if os.IsNotExist(err) {
		return os.MkdirAll(dir, perm)
	} else if err == nil {
		if (info.Mode().Perm() | perm) == info.Mode().Perm() {
			return nil
		} else {
			return fmt.Errorf("Permission denied. want:%s, have:%s", perm.String(), info.Mode().String())
		}
	}

	return err
}
